package com.lagou.server;

import com.lagou.RpcDecoder;
import com.lagou.RpcEncoder;
import com.lagou.handler.UserServerHandler;
import com.lagou.pojo.RpcRequest;
import com.lagou.registry.ServiceRegistry;
import com.lagou.serializer.JSONSerializer;
import com.lagou.service.UserService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

/**
 * @author 陶肖寅
 * @version V1.0
 * @Package com.lagou.server
 * @email fromlx@126.com
 * @date 2020-03-23 21:43
 * @Copyright © 2020-2021 城云科技(中国)有限公司
 */
@Component
public class UserServerImpl implements UserService {
    /**
     * 服务名称
     */
    private static final String SERVICE_NAME = "netty_service";
    /**
     * 注册中心地址
     */
    private static final String SERVER_ADDRESS = "118.31.175.207:2181";
    @Override
    public String sayHello(String word) {
        System.out.println("调用成功--参数 "+word);
        return word;
    }

    /**
     * server启动类
     * @param hostName 主机地址
     * @param port 端口号
     */
    public void startServer(String hostName,int port) throws InterruptedException {
        //接收请求
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        //处理请求
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boosGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(RpcRequest.class,new JSONSerializer()));
//                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new UserServerHandler());
                    }
                });
        bootstrap.bind(hostName,port).sync();
        //注册到zK中心
        ServiceRegistry registry = new ServiceRegistry(SERVER_ADDRESS);
        registry.register(hostName+":"+port);
    }
}
